const mongoose = require('mongoose');
//  教程： https://mongoose.nodejs.cn/docs/index.html#google_vignette
// const { MongoMemoryServer } = require('mongodb-memory-server');
// const mongod = new MongoMemoryServer();
mongoose.connect('mongodb://127.0.0.1:27017/TestDB');
mongoose.connection.on('error', console.error.bind(console, '连接失败：')); 

mongoose.connection.once('open', function() {
    console.log("连接成功");
    let BookSchema = new mongoose.Schema({
        name: String,
        author: String,
        tags: [String],
        date: { type: Date, default: Date.now },
        isPublished: Boolean
    });
    // 编译模型
    let BookModel = mongoose.model('Book', BookSchema);

    BookModel.create({
        name: 'TypeScript 入门',
        author: '李柳',
        tags: ['ts', 'js'],
        isPublished: true
    })
    .then(doc => {
        console.log('插入成功:', doc)
        mongoose.disconnect();
    })
    .catch(err => console.error('插入失败:', err))
    
});


mongoose.connection.once('open', function() {
    console.log("连接成功");
    let GoodsSchema = new mongoose.Schema({
        name: String,
        price: Number
    });
    // 编译模型
    let GoodModel = mongoose.model('goods', GoodsSchema);

    GoodModel.create(   
        {
            name: '手机',
            price: 1000
        }   
    ).then(doc => {
        console.log('插入成功:', doc)
        mongoose.disconnect();
    })
    .catch(err => console.error('插入失败:', err))
    
});

mongoose.connection.on('close', function() {
    console.log("连接关闭");
});
// // 超时关闭
// setTimeout(() => {
//     mongoose.connection.close();
// }, 10000);
module.exports = {
    mongoose
}

